const 元转分 = num => Number((num * 100).toFixed());
// 时间戳产生函数  
const createTimeStamp = () => parseInt(new Date().getTime() / 1000).toString()
// 随机字符串产生函数
const createNonceStr = () => Math.random().toString(36).substr(2, 15)
//生成随机字符串
const randomString = (len = 32) => {
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) { pwd += chars.charAt(Math.floor(Math.random() * maxPos)); }
    return pwd;
}
const express = require('express')
const request = require('request')
const router = express.Router()
const crypto = require('crypto');
const xml2js = require('xml2js');
const toXml = new xml2js.Builder();// json->xml
module.exports = app => {
    const appid = 'wx3f8607ee708aaccb';  // 小程序的appid
    const appsecret = 'ad24a96dbb0adc646c03b1008ebc7759'; // 小程序的appSecret
    const mchid = '1521320581'; // 微信商户号
    const mch_key = 'wSV7IfyOHUPYv1MOt8nHckEVOX7cGOhf';  // 微信商户的key 32位
    const callbackUrl = '47.100.123.109:80'; //通知地址

    router.get('/wxpayss', (req, res) => {
        let orderCode = req.query.paySign
        let money = req.query.price
        let openid = req.query.openid

        let 请求参数 = {
            appid,//应用Id
            mch_id,//商户号	
            nonce_str: randomString(32),//随机字符串,随机数生成算法
            openid,
            body: "测试微信支付",//商品描述	
            out_trade_no: orderCode,//订单号商户系统内部订单号
            total_fee: 元转分(money),//金额
            spbill_create_ip: req.connection.remoteAddress,//用户端实际ip  支持IPV4和IPV6两种格式的IP地址。调用微信支付API的机器IP
            notify_url: callbackUrl,//微信付款后的回调地址
            trade_type: 'JSAPI',//交易类型 'APP';公众号：'JSAPI'或'NATIVE'
        };
        请求参数.sign = getSign(请求参数, mch_key);
        请求参数 = toXml.buildObject(请求参数);

        var url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        request({ url: url, method: 'POST', body: 请求参数 }, function (err, response, body) {
            console.log({ err, response, body })
        });
    })
    app.use('/api', router)
}

//签名算法
function getSign(paramSign, key) {
    //按key值的ascii排序
    const keys = Object.keys(paramSign).sort();
    let temp = [];
    keys.forEach(v => {
        if (paramSign[v] && v !== 'sign') {
            temp.push(`${v}=${paramSign[v]}`);
        }
    });
    temp.push(`key=${key}`);
    const ret = temp.join('&');
    //生成签名
    return crypto.createHash('md5').update(ret, 'utf8').digest('hex').toUpperCase();
}